package com.snail.file.service.impl;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.snail.common.core.utils.file.FileTypeUtils;
import com.snail.file.config.FileConfigProperties;
import com.snail.file.property.FastDfsFile;
import com.snail.system.api.domain.SysFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * FastDFS 文件存储
 *
 * @author snail
 */
@Service("fastDfsSysFileService")
public class FastDfsSysFileServiceImpl {

    @Autowired
    private FileConfigProperties properties;

    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * FastDfs文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    public String uploadFile(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        StorePath storePath = storageClient.uploadFile(inputStream, file.getSize(),
                FileTypeUtils.getExtension(file), null);
        return properties.getFastDfs().domain + "/" + storePath.getFullPath();
    }

    /**
     * 下载附件
     * @param file 附件信息
     * @return 结果
     */
    public InputStream download(SysFile file) {
        FastDfsFile fastDfs = properties.getFastDfs();
        return storageClient.downloadFile(fastDfs.getGroupName(),file.getFileUrl(), ins -> ins);
    }

    /**
     * 删除文件
     * @param file 文件信息
     */
    public void delete(SysFile file) {
        FastDfsFile fastDfs = properties.getFastDfs();
        storageClient.deleteFile(fastDfs.groupName,file.getFileUrl());
    }
}
